<?php

/**
 * Plugin zajistuje autentifikaci uzivatele a presmerovani
 *
 */
class Application_Plugin_FbAuth extends Zend_Controller_Plugin_Abstract
{

    /**
     *
     * @var array
     */
    private $_options;

    /**
     * Metoda vrati konkretni hodnotu z konfigurace
     * Pokud klic neni nalezen, vyhodime vyjimku
     *
     * @param string $key
     * @return mixed
     */
    private function _getParam($key)
    {
        if (is_null($this->_options))
        {
            $this->_options = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getApplication()->getOptions();
        }

        if (!array_key_exists($key, $this->_options['facebook']))
        {
            throw new Zend_Controller_Exception("Param {facebook.$key} not found in application.ini");
        }
        else
        {
            return $this->_options['facebook'][$key];
        }
    }

    /**
     * Wrapper nad metodou _getParam
     * Umozni nam pristupovat ke konfiguraci primo pres $this
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->_getParam($key);
    }

    /**
     * Enter description here...
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        // ziskame instanci redirector helperu, ktery ma starosti presmerovani
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');

        if ($request->getActionName() == 'logout')
        {
            return;
        }

        $auth = Zend_Auth::getInstance();
        // Stav o autentifikaci uzivatele (prihlaseni) se musi nekde udrzovat, vychozi zpusob je session
        // u session lze nastavit namespace, vychozi je Zend_Auth
        //$auth->setStorage(new Zend_Auth_Storage_Session('My_Auth'));


        $facebook = new Facebook(array(
                    'appId' => $this->app_key,
                    'secret' => $this->app_secret,
                    'cookie' => false,
                ));
        $session = $facebook->getSession();

        $me = null;
// Session based API call.
        if ($session)
        {
            try
            {
                $uid = $facebook->getUser();
//    $me = $facebook->api('/me');

                $data = $facebook->api(array('method' => 'users.getInfo', 'uids' => $uid, 'fields' => 'first_name,last_name,email,locale'));

                $facebook_data = $data[0];


                $users = new Users();

                $user = $users->findByEmail($facebook_data['email'])->current();

                if (empty($user))
                {
                    $user = $users->createRow();
                }

                $user->first_name = $facebook_data['first_name'];
                $user->last_name = $facebook_data['last_name'];
                $user->email = $facebook_data['email'];
                $user->locale = $facebook_data['locale'];
                $user->facebook_id = $uid;
                $user->save();
                
            }
            catch (FacebookApiException $e)
            {
                error_log($e);
            }

            if ($uid)
            {

                $adapter = new My_Auth_Adapter_Facebook($facebook);

                $result = $auth->authenticate($adapter);


                $users = new Users();
                $email = $facebook_data['email'];
                $r = $users->findByEmail($email);

                if (!empty($r))
                {
                    $user = $r->current();

                    $db = Zend_Db_Table::getDefaultAdapter();


                  $db->update('user', array(
                  'lognum' => new Zend_Db_Expr('lognum + 1'),
                  'ip' => $request->getClientIp(),
                  'last_login' => new Zend_Db_Expr('NOW()'),
                  'browser' => $request->getServer('HTTP_USER_AGENT')),
                  "email = '$email'");


                    if (empty($user->last_fm_username) && $request->getActionName() != 'account')
                    {
                        $redirector->gotoRoute(array('controller' => 'user', 'action' => 'account'));
                    }
                }

                if ($request->getQuery('session'))
                {
                    $redirector->gotoRoute(array('controller' => 'index', 'action' => 'index'), 'default', true);
                }
            }
        }


        
        
    }

}